package com.example.springcloud.controller;

import com.example.springcloud.commons.CommonResult;
import com.example.springcloud.entities.Payment;
import com.example.springcloud.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author weiHuang.zhu
 * @Date 9/4/2023 下午2:21
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {
    @Autowired
    private IPaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment) {
        int i = paymentService.create(payment);
        log.info("*** 插入结果***" + i);
        if (i > 0) {
            return new CommonResult(200, "插入数据库成功", i);
        } else {
            return new CommonResult(200, "插入数据库失败", null);
        }
    }

    @GetMapping("/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id")Long id) {
        int i = 1;
        Payment paymentById = paymentService.getPaymentById(id);
        if (Objects.nonNull(paymentById)) {
            return new CommonResult(200, "查询成功"+ serverPort, paymentById);
        } else {
            return new CommonResult(200, "没有记录", null);
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("element:"+service);
        }
        log.info("------------------");
        String serviceId = "PAYMENT-SERVICE";
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        for (ServiceInstance instance : instances) {
            log.info(instance.getInstanceId()+"\t" + instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/lb")
    public String getServerPort(){
        return serverPort;
    }

    //模拟超时
    @GetMapping("/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
